<?php
namespace App\Http\Controllers;

use App\Http\Requests\ArticleStatisticRequest;
use App\Models\Article;
use App\Models\Statistic;
use Illuminate\Http\Request;
use \Excel;
class ArticleStatisticController extends CommonController
{

    /**
     * 获取文章统计页面
     */
    public function getIndex()
    {
        $total = Article::count();

        return view('articlestatistic.index')->with('total', $total);
    }

    /**
     * 获取文章发布统计页面
     */
    public function getPub()
    {
        return view('articlestatistic.pub');
    }

    /**
     * 获取文章点击页面
     */
    public function getClick()
    {
        return view('articlestatistic.click');
    }

    /**
     * 获取文章统计页面
     */
    public function getStatistic()
    {
        return view('articlestatistic.statistic');
    }

    /**
     *ajax获取用户日项目发布数据
     */
    public function getDayPub()
    {
        $day = 24 * 3600;
        $today_zero = strtotime('today');
        //获取今天差几个小时
        $rest = sprintf("%.2f", (24 - (time() - $today_zero) / 3600));

        $date = array();
        //获取前31天的每天凌晨的时间戳,过去的时间排在前面
        $stamps = array();
        for ($i = 30; $i >= 0; $i--) {
            $stamps[] = $today_zero - $i * $day;
            $i > 0 && $date[] = date('m-d', strtotime(-$i . " day"));
        }

        $counts = array();
        for ($i = 1; $i < 31; $i++) {
            //获取前三十天的发布数据，过去的数据放在前面
            $counts[] = Article::whereBetween('created_at', [$stamps[$i - 1], $stamps[$i]])->count();
        }

        $counts[] = Article::whereBetween('created_at', [$today_zero, time()])->count();
        $date[] = '今天差' . $rest . '小时';

        $arr = [];
        foreach ($date as $k => $i) {
            $arr[] = array($i, $counts[$k]);
        }

        echo json_encode($arr);
    }

    /**
     *ajax获取用户周项目发布数据
     */
    public function getWeekPub()
    {
        //获取本周还剩下几天
        $rest = (8 - date('w')) % 7;
        $rest == 0 && $rest = 7;

        //获取本周一凌晨时间戳
        $thisMonday = strtotime('today') - (7 - $rest) * 24 * 3600;

        // 定义一周的时间戳
        $week = 7 * 24 * 3600;

        //获取前30周的每周一凌晨的时间戳,从前往后排
        $stamps = array();
        $date = array();

        for ($i = 30; $i >= 0; $i--) {
            $stamps[] = $thisMonday - $i * $week;
            $i > 0 && $date[] = '前' . ($i) . '周';
        }

        $counts = array();
        for ($i = 1; $i < 31; $i++) {
            $counts[] = Article::whereBetween('created_at', [$stamps[$i - 1], $stamps[$i]])->count();
        }
        $counts[] = Article::whereBetween('created_at', [$thisMonday, time()])->count();
        $date[] = '本周差' . $rest . '天';

        $arr = [];
        foreach ($date as $k => $i) {
            $arr[] = array($i, $counts[$k]);
        }

        echo json_encode($arr);
    }

    /**
     *ajax获取用户月项目发布数据
     */
    public function getMonthPub()
    {
        //获取本月还剩下多少天
        $rest = date('t') - date('j') + 1;
        //获取本月1号凌晨的时间戳
        $thisMonth = strtotime(date('Y-m-01'));
        //获取过去十三个月的，每个月1号凌晨的时间戳，从前往后
        $m = date('m');
        $y = date('Y');
        $stamps = array();
        for ($i = 0; $i < 13; $i++) {
            $newM = $m - $i;
            if ($newM <= 0) {
                $newM += 12;
                $y = $y - 1;
            }
            $stamps[] = strtotime($y . '-' . $newM . '-01');
            $y = date('Y');
        }

        $counts = array();
        for ($i = 12; $i > 0; $i--) {
            //获取前12个月的发布数据，过去的数据放在前面
            $counts[] = Article::whereBetween('created_at', [$stamps[$i], $stamps[$i - 1]])->count();
        }

        $date = array();
        for ($i = 12; $i > 0; $i--) {
            //获取前12个月的文字表述，过去的表述放在前面
            $date[] = $m - $i < 1 ? '去年' . ($m - $i + 12) . '月' : $m - $i . '月';
        }

        $counts[] = Article::whereBetween('created_at', [$thisMonth, time()])->count();
        $date[] = '本月差' . $rest . '天';

        $arr = [];
        foreach ($date as $k => $i) {
            $arr[] = array($i, $counts[$k]);
        }

        echo json_encode($arr);
    }

    /**
     *ajax获取日点击数据
     */
    public function getDayClick()
    {
        $date = array();
        //获取过去30天的文字表述
        for ($i = 30; $i >= 0; $i--) {
            $date[] = explode('-', date('Y-m-d', strtotime(-$i . " day")));
        }

        $counts = array();
        foreach ($date as $v) {
            $counts[$v[1] . '-' . $v[2]] = Statistic::where('year', $v[0])->where('month', $v[1])->where('day', $v[2])->count();
        }

        $arr = [];
        foreach ($counts as $k => $v) {
            $arr[] = array($k, $v);
        }

        echo json_encode($arr);
    }

    /**
     * 以Excel表格形式导出数据
     *
     */
    public function getExport(Request $request)
    {
        $data = $request->input();
        if(!$data['type'] || $data['type']==''){
            return $this->tip('操作错误，请选择类型', url('articlestatistic/statistic'), false);
        }

        if(!$data['begin_time'] || $data['begin_time']==''){
            return $this->tip('操作错误，请选择开始时间', url('articlestatistic/statistic'), false);
        }

        if(!$data['end_time'] || $data['end_time']==''){
            return $this->tip('操作错误，请选择结束时间', url('articlestatistic/statistic'), false);
        }

        $data['end_time'] = strtotime($data['end_time']);
        $data['begin_time'] = strtotime($data['begin_time']);
        $articles = Article::with('articleCategory')->whereBetween('created_at', [$data['begin_time'], $data['end_time']])->get()->toArray();

//        dd($articles);

        $title = [["id" =>'文章id',"category" =>'目录',"subject" =>'标题',"title" =>'副标题',
                   "created_at" =>'添加时间',"updated_at" =>'更新时间',"pubdate" =>'发布时间',"views" =>'浏览量'
            ,"source" =>'来源',"source_url" =>'来源网址',"copyrights" =>'版权',"recommend" =>'是否推荐'
        ],];

        $articlesInfo = array();
        foreach($articles as $k=>$v){
            $articlesInfo[$k]['id'] = $v['id'];
            $articlesInfo[$k]['category'] = $v['article_category']['name'];
            $articlesInfo[$k]['subject'] = $v['subject'];
            $articlesInfo[$k]['title'] = $v['title'];
            $articlesInfo[$k]['title'] = $v['title'];
            $articlesInfo[$k]['created_at'] = date('Y-m-d H:i:s', $v['created_at']);
            $articlesInfo[$k]['updated_at'] = date('Y-m-d H:i:s', $v['updated_at']);
            $articlesInfo[$k]['pubdate'] = date('Y-m-d H:i:s', $v['pubdate']);
            $articlesInfo[$k]['views'] = $v['views'];
            $articlesInfo[$k]['source'] = $v['source'];
            $articlesInfo[$k]['source_url'] = $v['source_url'];
            $articlesInfo[$k]['copyrights'] = $v['copyrights'];
            $articlesInfo[$k]['recommend'] = $v['recommend'] ?'推荐':'不推荐';
        }
        $articlesInfo = array_merge($title, $articlesInfo);
        Excel::create('文章发布列表', function($excel) use($articlesInfo) {
            $excel->sheet('文章发布列表', function($sheet) use($articlesInfo) {
                $sheet->rows($articlesInfo);
            });
        })->export('xls');
    }

    /**
     *异步获取
     */
    public function postFind(ArticleStatisticRequest $request)
    {
        $data = $request->input();
        $data['end_time'] = strtotime($data['end_time']);
        $data['begin_time'] = strtotime($data['begin_time']);
        $articles = Article::with('articleCategory')->whereBetween('created_at', [$data['begin_time'], $data['end_time']])->paginate(10);
//        dd($articles);
        $return_date = array();
        $articles_data = array();
        foreach ($articles as $k => $v) {
            $articles_data[$k]['id'] = $v->id;
            $articles_data[$k]['subject'] = cut_str($v->subject,8,'...');
            $articles_data[$k]['source'] = $v->source;
            $articles_data[$k]['category'] = isset($v->articleCategory->name)?$v->articleCategory->name:'';
            $articles_data[$k]['views'] = $v->views;
            $articles_data[$k]['status'] = $v->status?'显示':'不显示';
            $articles_data[$k]['created_at'] = date('Y-m-d', strtotime($v->created_at->toDateTimeString()));
//            dd(date('Y-m-d', strtotime($v->created_at->toDateTimeString())));
        }
        $return_date['list'] = $articles_data;
        $return_date['page'] = $articles->render(true);

        return AjaxCallbackMessage($return_date, true);
    }
}